package com.sctu.adapter;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.util.Base64;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.*;
import com.alibaba.fastjson.JSON;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.sctu.EMSApp.LoginActivity;
import com.sctu.EMSApp.MyTravelNoteActivity;
import com.sctu.EMSApp.R;
import com.sctu.bean.TravelNotesListBean;
import com.sctu.bean.TravelNotesListPostBean;
import com.sctu.http.UrlConfig;
import com.sctu.httpvollry.GetVolleyHttp;
import com.sctu.util.SharePreferenceUtil;
import com.sctu.view.CustomImageView;

import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by 鑫爷您慢点 on 2015/12/24.
 */
public class TravelNotesListAdapter extends BaseAdapter implements View.OnClickListener {
    private Activity activity;
    private List<TravelNotesListBean.Results> list = new ArrayList<TravelNotesListBean.Results>();
    private ImageView reprintImg, clickLikeImg, commentsImg, senBtn;//头像 转载 点赞 评论
    private CustomImageView headImg;
    private TextView nameTxt, timeTxt, titleTxt, contentTxt, readTxt, commentsPerson, commentsContent, clickLikePerson;
    private HashMap<Integer, LinearLayout> hashMap = new HashMap<Integer, LinearLayout>();
    private int tag;
    private List<Bitmap> bitmapList = new ArrayList<Bitmap>();

    /**
     * 构造函数
     *
     * @param activity
     * @param list
     */
    public TravelNotesListAdapter(Activity activity, List<TravelNotesListBean.Results> list) {
        this.activity = activity;
        this.list = list;
        bitmapList = getHeadImg(list);
    }

    public TravelNotesListAdapter() {

    }

    /**
     * 获取头像
     * @param list1
     * @return
     */
    private List<Bitmap> getHeadImg(final List<TravelNotesListBean.Results> list1){
        final List<Bitmap> bitmapList1 = new ArrayList<Bitmap>();
        new Thread() {
            @Override
            public void run() {
                for (int i = 0; i < list1.size(); i++) {
                    Bitmap bitmap = null;
                    try {
                        URL URLimage = new URL(UrlConfig.URL + list1.get(i).getHeadimages());
                        URLConnection urlConnection = URLimage.openConnection();
                        urlConnection.setDoInput(true);
                        urlConnection.connect();
                        InputStream in = urlConnection.getInputStream();
                        bitmap = BitmapFactory.decodeStream(in);
                    } catch (java.io.IOException e) {
                        e.printStackTrace();
                    }
                    bitmapList1.add(bitmap);
                }
            }
        }.start();
        return bitmapList1;
    }


    @Override
    public int getCount() {
        if (list != null && list.size() > 0) {
            return list.size();
        } else {
            return 0;
        }
    }

    @Override
    public Object getItem(int position) {
        return list.size();
    }

    @Override
    public long getItemId(int position) {
        return list.size();
    }

    @Override
    public View getView(final int position, View view, ViewGroup parent) {

        view = LayoutInflater.from(activity).inflate(R.layout.item_activity_travel_notes_list, null);
        headImg = ((CustomImageView) view.findViewById(R.id.item_travel_notes_list_head_photo));
        nameTxt = ((TextView) view.findViewById(R.id.item_travel_notes_list_name_txt));
        timeTxt = ((TextView) view.findViewById(R.id.item_travel_notes_list_time_txt));
        titleTxt = ((TextView) view.findViewById(R.id.item_travel_notes_list_title_txt));
        contentTxt = ((TextView) view.findViewById(R.id.item_travel_notes_list_content_txt));
        reprintImg = ((ImageView) view.findViewById(R.id.item_travel_notes_list_zhuanzai_img));
        clickLikeImg = ((ImageView) view.findViewById(R.id.item_travel_notes_list_zan_img));
        commentsImg = ((ImageView) view.findViewById(R.id.item_travel_notes_list_pinlun_img));
        readTxt = ((TextView) view.findViewById(R.id.item_travel_notes_list_read_number_txt));
        clickLikePerson = ((TextView) view.findViewById(R.id.item_travel_notes_list_zan_person));
        final EditText editText = ((EditText) view.findViewById(R.id.item_travel_notes_list_editText));
        senBtn = ((ImageView) view.findViewById(R.id.item_travel_notes_list_send_btn));
        final LinearLayout linearLayout = ((LinearLayout) view.findViewById(R.id.item_travel_notes_list_pinlun_lay));
        hashMap.put(position, linearLayout);

        nameTxt.setText(list.get(position).getAuthor());
        timeTxt.setText(list.get(position).getPubdate());
        titleTxt.setText(list.get(position).getTitle());
        //设置头像
        try {
            if (!bitmapList.isEmpty() && bitmapList.get(position) != null) {
                headImg.setmSrc(bitmapList.get(position));
            }
        }catch (java.lang.IndexOutOfBoundsException e ){
            e.printStackTrace();
        }
        for (int i = 0; i < list.get(position).getCommentJsonList().size(); i++) {
            linearLayout.addView(createLin(activity, list.get(position).getCommentJsonList().get(i).getName(),
                    list.get(position).getCommentJsonList().get(i).getContent()));
        }

        String content = "";
        if (list.get(position).getContent().length() > 80) {//如果内容过多，截取显示
            content = list.get(position).getContent().substring(0, 80) + "···>>";
        } else {
            content = list.get(position).getContent();
        }
        contentTxt.setText(content);
        reprintImg.setOnClickListener(this);
        clickLikeImg.setOnClickListener(this);
        commentsImg.setOnClickListener(this);
        contentTxt.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                MyTravelNoteActivity.actionStart(String.valueOf(list.get(position).getId()), activity);
            }
        });
        senBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               String isLogin = SharePreferenceUtil.getInstance(activity).getKeyData("islogin");
                if (isLogin != null && isLogin != "" && isLogin.equals("1")){
                    String comment = editText.getText().toString();
                    tag = position;
                    HashMap<String, String> map = new HashMap<String, String>();
                    map.put("uid", String.valueOf(SharePreferenceUtil.getInstance(activity).getKeyData("userId")));
                    map.put("content", comment);
                    if (!comment.isEmpty() && !comment.equals("") && comment != null) {
                        GetVolleyHttp.getInstance(activity).getStringPOSTJsonData(UrlConfig.URL_TRAVEL_NOTES_LIST_COMMENT + String.valueOf(list.get(position).getId()), map,
                                listener, errorlistener);
                    } else {
                        Toast.makeText(activity, "评论不能为空", Toast.LENGTH_LONG)
                                .show();
                    }
                    editText.setText("");
                }else {
                    AlertDialog.Builder dialog = new AlertDialog.Builder(activity);
                    dialog.setTitle("请登录");
                    dialog.setCancelable(true);
                    dialog.setNegativeButton("取消", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                        }
                    });
                    dialog.setPositiveButton("登陆", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            Intent intent = new Intent();
                            intent.setClass(activity, LoginActivity.class);
                            activity.startActivity(intent);
                        }
                    });
                    dialog.show();
                }
            }
        });
        return view;
    }
    Response.Listener<String> listener = new Response.Listener<String>() {
        @Override
        public void onResponse(String json) {
            Log.e("json", json);
            TravelNotesListPostBean travelNotesListPostBean = JSON.parseObject(json, TravelNotesListPostBean.class);
            if (travelNotesListPostBean.getCode() == 0) {
                for (int i = 0; i < travelNotesListPostBean.getResults().size(); i++) {
                    hashMap.get(tag).addView(createLin(activity, travelNotesListPostBean.getResults().
                            get(i).getName(), travelNotesListPostBean.getResults().get(i).getContent()));
                }
            } else {
                Toast.makeText(activity, "评论失败", Toast.LENGTH_LONG)
                        .show();
            }
        }
    };
    // 当网络请求返回状态不成功（也就不是200）
    Response.ErrorListener errorlistener = new Response.ErrorListener() {

        @Override
        public void onErrorResponse(VolleyError arg0) {
            Toast.makeText(activity, "网络出了些小问题qqq", Toast.LENGTH_LONG)
                    .show();
        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.item_travel_notes_list_zhuanzai_img:
                Toast.makeText(activity, "zhuanzai", Toast.LENGTH_SHORT).show();
                break;
            case R.id.item_travel_notes_list_zan_img:
                Toast.makeText(activity, "zan", Toast.LENGTH_SHORT).show();
                break;
            case R.id.item_travel_notes_list_pinlun_img:
                Toast.makeText(activity, "pinlun", Toast.LENGTH_SHORT).show();
                break;
            case R.id.item_travel_notes_list_head_photo:
                Toast.makeText(activity, "headPhoto", Toast.LENGTH_SHORT).show();
                break;
            default:
                break;
        }
    }

    /**
     * @param base64Data
     * @return
     */
    public static Bitmap base64ToBitmap(String base64Data) {
        byte[] bytes = Base64.decode(base64Data, Base64.DEFAULT);
        return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
    }

    /**
     * 生成含有两个TextView的LinearLayout
     *
     * @param context
     * @param person
     * @param content
     * @return
     */
    private static LinearLayout createLin(Context context, final String person, final String content) {
        LinearLayout linearLayout = new LinearLayout(context);
        LinearLayout.LayoutParams margin = new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        TextView textViewPerson = new TextView(context);
        TextView textViewContent = new TextView(context);
        textViewPerson.setText(person + "：");
        textViewPerson.setTextColor(Color.BLUE);
        textViewContent.setTextColor(Color.BLACK);
        textViewContent.setText(content);
        linearLayout.addView(textViewPerson, margin);
        linearLayout.addView(textViewContent, margin);
        return linearLayout;
    }
}
